package com.hwl.lab.controller;

import com.hwl.lab.entity.Menu;
import com.hwl.lab.entity.User;
import com.hwl.lab.service.MenuService;
import com.hwl.lab.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin //允许跨域请求
@RestController
public class MenuController {

    @Autowired
    private MenuService menuService;

    //查询所有(分页)
    @GetMapping("/findMenuAll/{page}/{size}")
    public Page<Menu> findMeMnuAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        return menuService.findAll(page,size);
    }
    //查询所有菜单(不分页),用于加载菜单树
    @GetMapping("/findMenuAllR")
    public List<Menu> findmenuAll() {
        List<Menu> menus = new ArrayList<>();
        menus = menuService.findAll();
        for (int n=0;n<menus.size();n++) {
            for (int i=0;i<5;i++) {
                if (menus.get(n).getLevel() == i) {
                    String cat = "";
                    for (int k=0;k<i;k++) {
                        cat=Integer.toString(k+1)+"级-";
                    }
                    menus.get(n).setMenuname( cat+menus.get(n).getMenuname());
                }
            }
        }
        return menus;
    }

    //账号查询
    @GetMapping("/findByMenuid/{userid}")
    public List<Menu> findByMenuid(@PathVariable("userid") String menuid){
        List<Menu> menu = new ArrayList<>();
        menu.add(menuService.findByMenuid(menuid));
        return menu;
    }
    //添加
    @PostMapping("/saveMenu")
    public void saveMenu(@RequestBody(required=false) Menu menu){
        Menu menup = menuService.findByMenuid(menu.getMenupid());
        String menupid = menu.getMenupid();
        for (int n = 1; n < 10; n++) {
            String id = Integer.toString(n);
            String num = menupid + "0" + id;
            Menu test = menuService.findByMenuid(num);
            if (test == null) {
                menu.setMenuid(num);
                break;
            }
        }
        menu.setLevel(menup.getLevel()+1);
        menuService.saveUser(menu);
    }
    //修改
    @PostMapping("/saveMenus")
    public void saveMenus(@RequestBody(required=false) Menu menu){
        menuService.saveUser(menu);
    }
    //通过账号删除
    @PostMapping("/deleteMenu/{id}")
    public void deleteMenu(@PathVariable("id") Long id){
        menuService.deleteById(id);
    }
}
